package com.resource.transactions.config;

import com.resource.transactions.security.MyFilterSecurityInterceptor;
import com.resource.transactions.security.UserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    private final MyFilterSecurityInterceptor myFilterSecurityInterceptor;

    @Autowired
    public SpringSecurityConfig(MyFilterSecurityInterceptor myFilterSecurityInterceptor) {
        this.myFilterSecurityInterceptor = myFilterSecurityInterceptor;
    }

    @Bean
    UserDetailsService customUserService(){
        return new UserDetailServiceImpl();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/css/**").permitAll()
                .antMatchers("/img/**").permitAll()
                .antMatchers("/css/fonts/*.woff").permitAll()
                .antMatchers("/css/fonts/*.woff2").permitAll()
                .antMatchers("/css/fonts/*.tff").permitAll()
                .antMatchers("/css/fonts/*.eot").permitAll()
                .antMatchers("/login").permitAll()
                .antMatchers("/index").permitAll()
                .antMatchers("/reset").permitAll()
                .antMatchers("/register").permitAll()
                .antMatchers("/smsverification").permitAll()
                .antMatchers("/resourceSearch/*").permitAll()
                .and()
                .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/userLogin")
                .successForwardUrl("/userLoginSuccess")
                .failureUrl("/userLoginError")
                .permitAll();
        http.sessionManagement().maximumSessions(1).expiredUrl("/login");
        http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserService());
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/static/**");
        web.ignoring().antMatchers("/mapper/**");
    }

}
